import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/common/utils/time_util.dart';
import 'package:oramemo/entity/voice_record_transliterate_entity.dart';
import 'package:oramemo/common/langs/text_key.dart';

class SearchDialog extends StatefulWidget {
  final List<VoiceRecordTransliterateSegments> segments;
  final Function(VoiceRecordTransliterateSegments) onItemSelected;

  const SearchDialog({
    Key? key,
    required this.segments,
    required this.onItemSelected,
  }) : super(key: key);

  @override
  State<SearchDialog> createState() => _SearchDialogState();
}

class _SearchDialogState extends State<SearchDialog> {
  final TextEditingController _searchController = TextEditingController();
  List<VoiceRecordTransliterateSegments> _searchResults = [];
  String _highlightText = '';

  @override
  void initState() {
    super.initState();
    _searchResults = widget.segments;
  }

  void _performSearch(String query) {
    setState(() {
      _highlightText = query;
      if (query.isEmpty) {
        _searchResults = widget.segments;
      } else {
        _searchResults = widget.segments
            .where((segment) =>
                segment.text?.toLowerCase().contains(query.toLowerCase()) ?? false)
            .toList();
      }
    });
  }

  Widget _buildHighlightedText(String text) {
    if (_highlightText.isEmpty) {
      return Text(text);
    }

    List<TextSpan> spans = [];
    final lowercaseText = text.toLowerCase();
    final lowercaseQuery = _highlightText.toLowerCase();
    int start = 0;

    while (true) {
      final index = lowercaseText.indexOf(lowercaseQuery, start);
      if (index == -1) {
        spans.add(TextSpan(text: text.substring(start)));
        break;
      }

      if (index > start) {
        spans.add(TextSpan(text: text.substring(start, index)));
      }

      spans.add(TextSpan(
        text: text.substring(index, index + _highlightText.length),
        style: const TextStyle(
          backgroundColor: Colors.yellow,
          fontWeight: FontWeight.bold,
        ),
      ));

      start = index + _highlightText.length;
    }

    return RichText(text: TextSpan(
      style: const TextStyle(color: Colors.black),
      children: spans,
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Container(
        width: double.maxFinite,
        height: MediaQuery.of(context).size.height * 0.8,
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // 搜索框
            TextField(
              controller: _searchController,
              autofocus: true,
              decoration: InputDecoration(
                hintText: TextKey.transcriptionDetailsSearch.tr,
                prefixIcon: const Icon(Icons.search),
                suffixIcon: IconButton(
                  icon: const Icon(Icons.clear),
                  onPressed: () {
                    _searchController.clear();
                    _performSearch('');
                  },
                ),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              onChanged: _performSearch,
            ),
            const SizedBox(height: 16),
            
            // 搜索结果
            Expanded(
              child: ListView.builder(
                itemCount: _searchResults.length,
                itemBuilder: (context, index) {
                  final segment = _searchResults[index];
                  return ListTile(
                    leading: Text(
                      _formatDuration(segment.start!),
                      style: const TextStyle(fontSize: 12),
                    ),
                    title: _buildHighlightedText(segment.text ?? ''),
                    onTap: () {
                      Navigator.pop(context);
                      widget.onItemSelected(segment);
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  String _formatDuration(String duration) {
    final start = (duration.toDouble() ?? 0) * 1000;
    return TimeUtils.formatDuration(Duration(milliseconds: start.toInt()));
  }
} 